package cn.samler.project.guestbook.controller;

import cn.samler.project.guestbook.annotation.IgnoreTokenCheck;
import cn.samler.project.guestbook.annotation.UserRoleIs;
import cn.samler.project.guestbook.annotation.UserStatusCheck;
import cn.samler.project.guestbook.entity.User;
import cn.samler.project.guestbook.model.common.Page;
import cn.samler.project.guestbook.model.common.Response;
import cn.samler.project.guestbook.model.request.MessageCreateRequest;
import cn.samler.project.guestbook.model.request.MessageModifyRequest;
import cn.samler.project.guestbook.model.request.MessageReplyRequest;
import cn.samler.project.guestbook.service.MessageService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Positive;

@RestController
@RequestMapping("message")
public class MessageController {
    private final MessageService messageService;

    public MessageController(MessageService messageService) {
        this.messageService = messageService;
    }

    /**
     * 列出留言列表
     *
     * @param page {@link Page}
     * @return {@link Response}
     */
    @GetMapping("list")
    @IgnoreTokenCheck
    public Response list(@Validated Page page) {
        return messageService.list(page);
    }

    /**
     * 创建留言
     *
     * @param request {@link MessageCreateRequest}
     * @return {@link Response}
     */
    @PostMapping("create")
    @UserStatusCheck
    @UserRoleIs({ User.Role.USER })
    public Response add(@RequestBody @Validated MessageCreateRequest request) {
        return messageService.create(request);
    }

    /**
     * 修改留言
     *
     * @param request {@link MessageModifyRequest}
     * @return {@link Response}
     */
    @PostMapping("modify")
    @UserStatusCheck
    @UserRoleIs({ User.Role.USER })
    public Response modify(@RequestBody @Validated MessageModifyRequest request) {
        return messageService.modify(request);
    }

    /**
     * 回复留言
     *
     * @param request {@link MessageReplyRequest}
     * @return {@link Response}
     */
    @PostMapping("reply")
    @UserStatusCheck
    @UserRoleIs({ User.Role.SUPER_ADMIN, User.Role.MESSAGE_PROCESSOR })
    public Response reply(@RequestBody @Validated MessageReplyRequest request) {
        return messageService.reply(request);
    }

    /**
     * 删除留言
     *
     * @param id 留言id
     * @return {@link Response}
     */
    @DeleteMapping("{id}")
    @UserStatusCheck
    @UserRoleIs({ User.Role.SUPER_ADMIN, User.Role.MESSAGE_PROCESSOR })
    public Response delete(@PathVariable("id") @Validated
                               @NotEmpty(message = "留言id不能为空")
                               @Pattern(regexp = "^\\d+$", message = "留言id有误")
                               @Positive(message = "留言id有误") Integer id) {
        return messageService.delete(id);
    }
}
